// pages/index/index.js
const { checkOrder, checkOrderForIdCard, uploadIdCard, submitIdCardUpload, searchLogistic } = require('../../services/logistic')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0, // 当前选中的tab，0-运单查询，1-上传身份证
    waybillNumber: '', // 运单号
    idWaybillNumber: '', // 身份证关联运单号
    idCardFront: '', // 身份证正面图片
    idCardBack: '', // 身份证背面图片
    userInfo: null,
    showPhoneModal: false,
    phoneLast4: '',
    pendingWaybill: '',
    orderId: '', // 订单ID
    idCardFrontData: null, // 身份证正面上传返回的数据
    idCardBackData: null, // 身份证背面上传返回的数据
    isQuerying: false, // 查询运单loading状态
    isUploading: false, // 上传身份证loading状态
    isVerifying: false, // 验证订单号loading状态
    showIdCardUpload: false, // 是否显示身份证上传区域
    isSubmitting: false, // 提交上传loading状态
    uploadComplete: false // 是否完成正反面上传
  },
  /**
   * 规范化运单号：
   * - 若为 URL，优先解析 query 中的 order_sn
   * - 否则返回去空格后的原始字符串
   */
  normalizeWaybill(input){
    const raw = String(input || '').trim()
    if (!raw) return ''
    // 尝试解析 URL 并提取 order_sn
    if (/^https?:\/\//i.test(raw)) {
      try {
        const queryStr = raw.split('?')[1] || ''
        const pairs = queryStr.split('&')
        for (let i = 0; i < pairs.length; i++) {
          const seg = pairs[i]
          const kv = seg.split('=')
          const k = decodeURIComponent(kv[0] || '')
          if (k === 'order_sn') {
            const v = decodeURIComponent(kv.slice(1).join('=') || '')
            return v.trim()
          }
        }
      } catch (e) {
        // ignore parse error and fallback to raw below
      }
    }
    return raw
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try{
      const user = wx.getStorageSync('user') || null
      this.setData({ userInfo: user })
    }catch(e){
      this.setData({ userInfo: null })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 切换Tab
   */
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      currentTab: tab
    });
  },

  /**
   * 运单号输入
   */
  onWaybillInput(e) {
    this.setData({
      waybillNumber: e.detail.value
    });
  },

  /**
   * 身份证关联运单号输入
   */
  onIdWaybillInput(e) {
    this.setData({
      idWaybillNumber: e.detail.value
    });
  },

  /**
   * 扫描条码
   */
  onScanCode() {
    wx.scanCode({
      success: (res) => {
        if (this.data.currentTab === 0) {
          // 运单查询tab：扫码后直接跳转
          const scanned = (res.result || '').trim()
          const normalized = this.normalizeWaybill(scanned)
          if (normalized) {
            wx.navigateTo({
              url: `/pages/track/track?waybill=${encodeURIComponent(normalized)}&carrier=${encodeURIComponent('顺丰快递')}&search_type=1`
            })
          } else {
            wx.showToast({ title: '无效条码', icon: 'none' })
          }
        } else {
          // 上传身份证tab
          this.setData({
            idWaybillNumber: res.result
          });
        }
        wx.showToast({
          title: '扫描成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '扫描失败',
          icon: 'error'
        });
      }
    });
  },

  /**
   * 查询物流
   */
  onQueryWaybill() {
    // 防止重复点击
    if (this.data.isQuerying) {
      return;
    }
    
    const waybillNumber = this.normalizeWaybill(this.data.waybillNumber);
    
    if (!waybillNumber) {
      wx.showToast({
        title: '请输入运单号',
        icon: 'none'
      });
      return;
    }
    
    // 设置loading状态
    this.setData({ isQuerying: true });
    
    // 校验单号是否正确，正确则弹出手机号后四位输入
    checkOrder({ scan_text: waybillNumber })
      .then((res) => {
        const ok = (res && (res.data && res.data.result === true))
        if (ok) {
          this.setData({ showPhoneModal: true, pendingWaybill: waybillNumber })
        } else {
          wx.showToast({ title: res.msg || '单号不正确', icon: 'none' })
        }
      })
        .catch((err) => {
          // 错误提示已在请求封装中处理
          wx.showToast({ title: err.msg || '单号不正确', icon: 'none' })
        })
      .finally(() => {
        // 清除loading状态
        this.setData({ isQuerying: false });
      })
  },

  onPhoneLast4Input(e){
    const raw = String(e.detail.value || '')
    const digitsOnly = raw.replace(/\D/g, '')
    this.setData({ phoneLast4: digitsOnly.slice(0,4) })
  },

  onCancelPhoneModal(){
    this.setData({ showPhoneModal: false, phoneLast4: '', pendingWaybill: '' })
  },

  async onConfirmPhoneModal(){
    const last4 = (this.data.phoneLast4 || '').trim()
    if (!/^\d{4}$/.test(last4)){
      wx.showToast({ title: '请输入4位数字', icon: 'none' })
      return
    }
    const waybill = this.data.pendingWaybill
    wx.showLoading({ title: '查询中...' })
    try{
      const params = { scan_text: waybill }
      params.search_type = 2
      params.check_phone = last4
      const res = await searchLogistic(params)
      if(res.code === 1) {
        this.setData({ showPhoneModal: false, phoneLast4: '' })
        wx.navigateTo({
          url: `/pages/track/track?waybill=${encodeURIComponent(waybill)}&carrier=${encodeURIComponent('顺丰快递')}&check_phone=${encodeURIComponent(last4)}&search_type=2`
        })
      } else {
        wx.showToast({ title: res.msg || '查询失败', icon:'none', duration: 5000 })
        setTimeout(() => {
          wx.hideLoading()
        }, 3000)
      }
    }catch(err){
      wx.showToast({ title:'查询失败', icon:'none', duration: 5000 })
      setTimeout(() => {
        wx.hideLoading()
      }, 3000)
    }
  },

  /**
   * 身份证关联运单号输入
   */
  onIdWaybillInput(e) {
    const value = e.detail.value.trim();
    this.setData({ 
      idWaybillNumber: value,
      showIdCardUpload: false // 输入时隐藏上传区域
    });
  },

  /**
   * 验证订单号按钮点击
   */
  onVerifyOrder() {
    const idWaybillNumber = this.data.idWaybillNumber.trim();
    
    if (!idWaybillNumber) {
      wx.showToast({
        title: '请输入订单号',
        icon: 'none'
      });
      return;
    }
    
    this.verifyOrderForIdCard(idWaybillNumber);
  },

  /**
   * 验证订单号
   */
  verifyOrderForIdCard(waybillNumber) {
    // 防止重复验证
    if (this.data.isVerifying) {
      return;
    }
    
    this.setData({ isVerifying: true });
    
    checkOrderForIdCard({ scan_text: waybillNumber })
      .then((res) => {
        if (res && res.data && res.data.result === true) {
          // 订单号验证成功，显示身份证上传区域
          const orderId = res.data.order_id;
          this.setData({ 
            orderId,
            showIdCardUpload: true
          });
        } else {
          wx.showToast({
            title: '订单号不正确',
            icon: 'none'
          });
        }
      })
      .catch((err) => {
        // 错误提示已在请求封装中处理
      })
      .finally(() => {
        this.setData({ isVerifying: false });
      });
  },

  /**
   * 上传身份证
   */
  onUploadIdCard(e) {
    // 防止重复点击
    if (this.data.isUploading) {
      return;
    }
    
    const type = e.currentTarget.dataset.type; // front 或 back
    
    // 检查是否已验证订单号
    if (!this.data.orderId) {
      wx.showToast({
        title: '请先验证订单号',
        icon: 'none'
      });
      return;
    }
    
    // 选择并上传图片
    this.chooseAndUploadImage(type, this.data.orderId);
  },

  /**
   * 选择并上传图片
   */
  chooseAndUploadImage(type, orderId) {
    // 设置上传loading状态
    this.setData({ isUploading: true });
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 确定上传类型
        const uploadType = type === 'front' ? 'font' : 'reverse';
        
        
        // 验证参数
        if (!tempFilePath) {
          wx.showToast({ title: '文件路径获取失败', icon: 'none' });
          this.setData({ isUploading: false });
          return;
        }
        
        if (!orderId) {
          wx.showToast({ title: '订单ID获取失败', icon: 'none' });
          this.setData({ isUploading: false });
          return;
        }
        
        uploadIdCard({
          file: tempFilePath,
          type: uploadType,
          order_id: orderId
        })
        .then((res) => {
          if (res && res.code === 1 && res.data) {
            // 上传成功，存储返回的数据
            if (type === 'front') {
              this.setData({
                idCardFront: tempFilePath,
                idCardFrontData: res.data
              });
            } else {
              this.setData({
                idCardBack: tempFilePath,
                idCardBackData: res.data
              });
            }
            
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            });
            
            // 更新上传完成状态
            this.updateUploadCompleteStatus();
          } else {
            wx.showToast({
              title: res.msg || '上传失败',
              icon: 'none'
            });
          }
        })
        .catch((err) => {
          // 错误提示已在请求封装中处理
        })
        .finally(() => {
          // 清除上传loading状态
          this.setData({ isUploading: false });
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        });
        // 清除上传loading状态
        this.setData({ isUploading: false });
      }
    });
  },

  /**
   * 更新上传完成状态
   */
  updateUploadCompleteStatus() {
    const { idCardFrontData, idCardBackData } = this.data;
    const uploadComplete = idCardFrontData && idCardBackData;
    this.setData({ uploadComplete });
  },

  /**
   * 检查上传是否完成
   */
  checkUploadComplete() {
    const { idCardFrontData, idCardBackData } = this.data;
    
    // 检查是否正反身份证都上传成功，但不自动提交
    return idCardFrontData && idCardBackData;
  },

  /**
   * 提交身份证上传
   */
  submitIdCardUpload() {
    // 防止重复提交
    if (this.data.isSubmitting) {
      return;
    }
    
    const { idCardFrontData, idCardBackData, orderId } = this.data;
    
    // 验证是否完成正反面上传
    if (!this.checkUploadComplete()) {
      wx.showToast({
        title: '请完成身份证正反面上传',
        icon: 'none'
      });
      return;
    }

    this.setData({ isSubmitting: true });
    
    // 调用提交上传API
    this.callUploadIdCardAPI();
  },

  /**
   * 调用上传身份证API
   */
  callUploadIdCardAPI() {
    const { idCardFrontData, idCardBackData, orderId } = this.data;
    
    // 调用真实的API
    submitIdCardUpload({
      order_id: orderId,
      ...idCardFrontData,
      ...idCardBackData
    })
    .then((res) => {
      if (res && res.code === 1) {
        wx.showToast({
          title: res.msg || '身份证上传成功',
          icon: 'success',
          duration: 3000
        });
      } else {
        wx.showToast({
          title: res.msg || '提交失败',
          icon: 'none'
        });
      }
    })
    .catch((err) => {
      // 错误提示已在请求封装中处理
    })
    .finally(() => {
      this.setData({ isSubmitting: false });
      // 重置状态，隐藏上传区域
      this.resetIdCardUpload();
    });
  },

  /**
   * 重置身份证上传状态
   */
  resetIdCardUpload() {
    this.setData({
      idWaybillNumber: '',
      idCardFront: '',
      idCardBack: '',
      orderId: '',
      idCardFrontData: null,
      idCardBackData: null,
      showIdCardUpload: false,
      isSubmitting: false,
      uploadComplete: false
    });
  },

  /**
   * 手动提交身份证上传（保留原方法名以兼容）
   */
  onSubmitIdCard() {
    if(!this.uploadComplete) {
      wx.showToast({
        title: '请完整上传正反面身份证',
        icon: 'none'
      });
    }
    this.submitIdCardUpload();
  },

  /**
   * 底部信息点击
   */
  onFooterTap() {
    if (this.data.userInfo) {
      return;
    }
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
})
